package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {


    @Autowired
    SendEmailCallback sendEmailCallback;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;



    private final String ORDER_GLOBAL_ID_CACHE_KEY="ORDER_ID";
    private final String ORDER_ITEM_GLOBAL_ID_CACHE_KEY="ORDER_ITEM_ID";
    @Override
    public TransCallback getTransCallback() {
        return sendEmailCallback;
    }

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 向下转型
        CreateOrderContext createOrderContext = ((CreateOrderContext) context);

        // 插入订单表
        Order order = new Order();
        // 用发号器生成订单id
        String orderId = globalIdGeneratorUtil.getNextSeq(OrderConstants.ORDER_ID, 1);
        // 给order赋值
        order.setOrderId(orderId);                                  // 订单id
        order.setPayment(createOrderContext.getOrderTotal());       // 订单金额
        order.setPaymentType(OrderConstants.PAYMENT_TYPE_ONLINE);   // 默认在线付款
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);          // 订单状态：未付款
        order.setCreateTime(new Date());                            // 创建日期
        order.setUpdateTime(new Date());                            // 更新日期
        order.setUserId(createOrderContext.getUserId());            // 用户id
        order.setBuyerNick(createOrderContext.getUserName());       // 用户表中没有昵称，就是用户名
        order.setUniqueKey(createOrderContext.getUniqueKey());      // 唯一键
        int orderInsert = orderMapper.insertSelective(order);
        // 如果插入失败，抛异常
        if (orderInsert < 1) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }

        // 插入订单商品关联表
        List<Long> buyProductIds = new ArrayList<>();
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto productDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            // 用发号器生成订单商品id
            String orderItemId = globalIdGeneratorUtil.getNextSeq(OrderConstants.ORDER_ITEM_ID, 1);
            orderItem.setId(orderItemId);
            orderItem.setItemId(productDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(productDto.getProductNum().intValue());
            orderItem.setTitle(productDto.getProductName());
            orderItem.setPrice(productDto.getSalePrice().doubleValue());
            BigDecimal totalFee = productDto.getSalePrice().multiply(new BigDecimal(productDto.getProductNum()));
            orderItem.setTotalFee(totalFee.doubleValue());
            orderItem.setPicPath(productDto.getProductImg());
            orderItem.setStatus(OrderConstants.ORDER_ITEM_STATUS_STOCK_LOCK);
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            // 商品id加入List
            buyProductIds.add(productDto.getProductId());
            // 插入记录
            int itemInsert = orderItemMapper.insert(orderItem);
            // 如果插入失败，抛异常
            if (itemInsert < 1) {
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }
        }
        // 填充 context，继续下一个handler
        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyProductIds);

        return true;
    }

}
